package cn.itcast.service.impl;

import cn.itcast.dto.SetmealDto;
import cn.itcast.entity.Page;
import cn.itcast.entity.SetmealDish;
import cn.itcast.exceptionHandler.CustomException;
import cn.itcast.mapper.ISetmealDishMapper;
import cn.itcast.mapper.ISetmealMapper;
import cn.itcast.service.ISetmealDishService;
import cn.itcast.service.ISetmealService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
public class SetmealServiceImpl implements ISetmealService {
    @Autowired(required = false)
    private ISetmealMapper setmealMapper;
    @Autowired
    private ISetmealDishService setmealDishService;
    @Autowired
    private ISetmealDishMapper setmealDishMapper;

    @Override
    @Transactional
    @CacheEvict(value = "setmealCache",allEntries = true)
    public void save(SetmealDto setmealDto) {
        setmealMapper.save(setmealDto);
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.forEach(setmealDish -> {
            Long setmealId = setmealDto.getId();
            setmealDish.setSetmealId(setmealId);
           setmealDishService.save(setmealDish);
        });

    }

    @Override
    public Page<SetmealDto> findByName(Integer pageNum, Integer pageSize, String name) {
        PageHelper.startPage(pageNum,pageSize);
        List<SetmealDto> list = setmealMapper.findByName(pageNum, pageSize, name);
        PageInfo<SetmealDto> pageInfo = new PageInfo<>(list);

        return new Page<>(pageInfo.getList(),pageInfo.getTotal(),pageSize,pageNum);
    }

    @Override
    public SetmealDto findById(Long id) {
        SetmealDto setmealDto = setmealMapper.findById(id);
        List<SetmealDish> setmealDishes = setmealDishService.findById(id);
        setmealDto.setSetmealDishes(setmealDishes);

        return setmealDto;
    }

    @Override
    @Transactional
    public void delete(Long[] ids) {
        int count = setmealMapper.findWithStatus(ids);
        if (count >0){
            throw new CustomException("套餐仍在售,禁止删除");
        }
        setmealMapper.delete(ids);
        setmealDishService.deleteBySetmealIds(ids);
    }

    @Override
    @Cacheable(cacheNames = "setmealCache",key = "#categoryId+'_'+#status")
    public List<SetmealDto> list(Long categoryId, Integer status) {
        return setmealMapper.list(categoryId,status);
    }

    @Override
    public List<Map<String, Object>> findSetmealDish(Long setmealId) {
        return setmealDishMapper.findSetmealDish(setmealId);
    }


}
